const { exec } = require('child_process');
const path = require('path');
const { TRANSITION_CONFIG, PATH_CONFIG } = require('../config/constants');
const { verifyFileExists, getFileSize } = require('../utils/fileUtils');

// 获取 FFmpeg 可执行文件路径
function getFFmpegPath() {
    const platform = process.platform === 'win32' ? 'windows' : 'linux';
    const version = platform === 'windows' ? 'release-essentials' : 'release-amd64-static';
    const binaryName = platform === 'windows' ? 'ffmpeg.exe' : 'ffmpeg';
    return path.join(PATH_CONFIG.ffmpegDir, 'extracted', platform, version, binaryName);
}

// 生成 FFmpeg 命令
function generateFfmpegCommand(imageFiles, config) {
    const {
        transition = TRANSITION_CONFIG.defaultTransition,
        duration = TRANSITION_CONFIG.defaultDuration,
        offset = TRANSITION_CONFIG.defaultOffset,
        fps = TRANSITION_CONFIG.defaultFps,
        width = TRANSITION_CONFIG.defaultWidth,
        height = TRANSITION_CONFIG.defaultHeight,
        totalDuration = TRANSITION_CONFIG.defaultTotalDuration
    } = config;

    console.log('生成FFmpeg命令，使用配置:', {
        transition,
        duration,
        offset,
        fps,
        width,
        height,
        totalDuration
    });

    const ffmpegPath = getFFmpegPath();
    const command = `"${ffmpegPath}" -loop 1 -framerate ${fps} -i "${imageFiles[0]}" -loop 1 -framerate ${fps} -i "${imageFiles[1]}" -filter_complex "[0:v]setpts=PTS-STARTPTS,scale=${width}:${height},fps=${fps}[v0];[1:v]setpts=PTS-STARTPTS,scale=${width}:${height},fps=${fps}[v1];[v0][v1]xfade=transition=${transition}:duration=${duration}:offset=${offset}[v]" -map "[v]" -c:v libx264 -preset medium -crf 23 -pix_fmt yuv420p -r ${fps} -t ${totalDuration}`;
    
    console.log('生成的FFmpeg命令:', command);
    return command;
}

// 视频生成任务
async function generateVideoTask(config) {
    const {
        imageFiles,
        outputPath,
        transition,
        duration,
        offset,
        fps,
        width,
        height,
        totalDuration
    } = config;

    return new Promise((resolve, reject) => {
        const ffmpegCommand = generateFfmpegCommand(imageFiles, {
            transition,
            duration,
            offset,
            fps,
            width,
            height,
            totalDuration
        }) + ` "${outputPath}"`;

        console.log('执行FFmpeg命令:', ffmpegCommand);

        exec(ffmpegCommand, (error, stdout, stderr) => {
            if (error) {
                console.error('FFmpeg 执行错误:', error);
                console.error('FFmpeg 错误输出:', stderr);
                reject(new Error('生成视频时出错: ' + error.message));
                return;
            }

            console.log('FFmpeg 执行完成');
            
            try {
                verifyFileExists(outputPath, '生成的视频文件');
                console.log('生成视频文件信息:', {
                    path: outputPath,
                    size: getFileSize(outputPath)
                });
                resolve(outputPath);
            } catch (err) {
                console.error('视频文件验证失败:', err);
                reject(new Error('视频文件生成失败'));
            }
        });
    });
}

module.exports = {
    generateVideoTask
}; 